
<script setup>
import {ref, reactive, onMounted} from 'vue';
import { ElMessage } from 'element-plus';
import {UpdateUser} from "@/api/user.js";
import {GetUser} from '@/api/user.js';

const dialogVisible = ref(false);
const userFormRef = ref(null);

const emits = defineEmits(['call-parent']);
const notifyParent = () => {
  emits('call-parent'); // 触发名为 'call-parent' 的自定义事件
};

const userForm = reactive({
  id:'',
  username: '',
  nickname: '',
  user_pic: '',
  user_role: '',
  password: '123456',
});

const rules = {
  username: [
    { required: true, message: '请输入账户', trigger: 'blur',},
    {
      min: 2,
      max: 20,
      message: '长度在 2 到 20 个字符',
      trigger: 'blur'
    }
  ],
  user_role: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入重置密码', trigger: 'blur',},
    {
      min: 5,
      max: 20,
      message: '长度在 5 到 20 个字符',
      trigger: 'blur'
    }
      ]
};

const handleAvatarChange = (file) => {
  userForm.user_pic = file.raw;
};

const UpdaterequestParam = ()=>{
  let param = {
    id: userForm.id,
    username: userForm.username,
    nickname: userForm.nickname===''?null:userForm.nickname,
    user_pic: userForm.user_pic===''?null:userForm.user_pic,
    password: userForm.password,
    user_role: userForm.user_role
  }
  return param;
}
const getUser = async(row)=>{
  console.log("row.id: ",row.id);
  const data = await GetUser(row.id);
  console.log("data: ",data);
  userForm.id = data.data.id;
  userForm.user_pic = data.data.user_pic;
  userForm.username = data.data.username;
  userForm.nickname = data.data.nickname;
  userForm.user_role = data.data.user_role;
}

const submitForm = async () => {
  if (!userFormRef.value) return;
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      // 这里可以添加提交表单的逻辑
      console.log('提交的表单数据:', userForm);
      await UpdateUser(UpdaterequestParam(userForm))
          .then(() => {
            // 提交成功后的逻辑
            ElMessage.success('提交成功');
            // 重置表单
            userFormRef.value.resetFields();
            // 关闭对话框
            notifyParent();
            setTimeout(async ()=>{
              ElMessage.info(`密码修改为${userForm.password} ，请告知用户。`);
            },3000)
            dialogVisible.value = false;
          })
          .catch((error) => {
            console.error('提交失败:', error);
            ElMessage.error('提交失败，请重试。');
            dialogVisible.value = false;
          });
    } else {
      ElMessage.error('表单验证失败，请检查必填项。');
    }
  });
};

// 暴露一个方法用于显示对话框
const showUpdateUserDialog = (row) => {
  userForm.id = row.id;
  getUser(row);
  dialogVisible.value = true;
};

defineExpose({
  showUpdateUserDialog
});
</script>

<template>
  <el-dialog v-model="dialogVisible" title="修改用户">
    <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="120px">
      <el-form-item label="账户" prop="username">
        <el-input v-model="userForm.username" />
      </el-form-item>
      <el-form-item label="用户昵称">
        <el-input v-model="userForm.nickname" />
      </el-form-item>
      <el-form-item label="用户头像">
        <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleAvatarChange"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户角色" prop="user_role">
        <el-select v-model="userForm.user_role" placeholder="请选择用户角色">
          <el-option label="管理员" value="admin" />
          <el-option label="普通用户" value="user" />
          <el-option label="被禁用户" value="ban" />
        </el-select>
      </el-form-item>
      <el-form-item label="用户密码" prop="password">
        <el-input v-model="userForm.password" type="password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>


<style scoped>
/* 可以添加自定义样式 */
</style>